﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using jmail;
using System.Collections;
using System.Data.SqlClient;
using System.Data.OleDb;



/// <summary>
/// cyly 的摘要说明
/// </summary>
public class cyly
{
    public static string OkQQ = "";

    /// <summary>
    /// 返回Url指定参数值
    /// </summary>
    /// <param name="ParameterName"></param>
    /// <returns></returns>
    public static string GetUrlParaValues(string ParameterName)
    {
        if (HttpContext.Current.Request.QueryString[ParameterName] != null)
        {
            return HttpContext.Current.Request.QueryString[ParameterName].ToString();
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// 信息提示
    /// </summary>
    /// <param name="message"></param>
    /// <param name="CustomEvent"></param>
    /// <param name="MsgType">显示方式</param>
    public static void MsgBox(string message, string CustomEvent, int MsgType)
    {
        if (message == null)
            message = "";
        message = message.Replace(" ", "");
        switch (MsgType)
        {
            case 1:
                System.Web.HttpContext.Current.Response.Write("<script defer>" + CustomEvent + ";alert('" + message + "');</script>");
                break;
        }
    }



    /// <summary>
    /// 切字串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="separator"></param>
    /// <returns></returns>
    static public string[] SplitString(string str, string separator)
    {
        string tmp = str;
        Hashtable ht = new Hashtable();
        int i = 0;
        int pos = tmp.IndexOf(separator);
        while (pos != -1)
        {
            ht.Add(i, tmp.Substring(0, pos));
            tmp = tmp.Substring(pos + separator.Length);
            pos = tmp.IndexOf(separator);
            i++;
        }
        ht.Add(i, tmp);
        string[] array = new string[ht.Count];
        for (int j = 0; j < ht.Count; j++)
            array[j] = ht[j].ToString();

        return array;
    }

    /// <summary>   
    /// 使用Jmail发送邮件的方法   
    /// </summary>   
    /// <param name="sender">发件人邮箱</param>   
    /// <param name="senderName">发件人姓名</param>   
    /// <param name="Receiver">收件人的地址</param>   
    /// <param name="subject">邮件的主题</param>   
    /// <param name="Content">邮件的内容</param>   
    /// <param name="ServerHost">邮件服务类型</param>   
    public static bool SendEmail(String sender, String senderName, String Receiver, String subject, String Content, string[] OkSmtp)
    {
        string TransmitName = "", TransmitPassWord = "", ServerHost = "";
        if (OkSmtp.Length == 3)
        {
            TransmitName = OkSmtp[1];
            TransmitPassWord = OkSmtp[2];
            ServerHost = OkSmtp[0];

            //TransmitName = "mail@38sy.com";
            //TransmitPassWord = "ydys";
            //ServerHost = "mail.38sy.com";
        }
        else
            return false;

        if (string.IsNullOrEmpty(TransmitName))
            return false;

        MessageClass jMessage = new MessageClass();
        jMessage.Charset = "GB2312";
        jMessage.ISOEncodeHeaders = false;
        jMessage.From = sender;
        jMessage.FromName = senderName;
        jMessage.Subject = subject;
        jMessage.MailServerUserName = TransmitName;
        jMessage.MailServerPassWord = TransmitPassWord;
        jMessage.AddRecipient(Receiver, "", "");
        jMessage.HTMLBody = Content;

        //判断上传控件是否为空   
        //if (fluAttachMent.HasFile)
        //{
        //    String fileName = fluAttachMent.PostedFile.FileName;
        //    //添加附件   
        //    jMessage.AddAttachment(fileName, true, "");
        //}
        //return false;

        try
        {
            if (jMessage.Send(ServerHost, false))
                return true;
            else
            return false;
        }
        catch
        {
            return false;
        }

    }



    /// <summary>
    /// 页面处理片断
    /// </summary>
    /// <returns></returns>
    public static string GetPageQQ(string Url, int Page, int isSendEmail, int isSaveData)
    {
        //处理page
        //Url = Url.Replace("begin=", "");
        Url += "&currpage=" + Page;


        string tb_intro = "";
        string tb_ifarm = "";

        string HtmlBody = spider.SpiderObj.GetRemoteHtmlCode(Url);
        HtmlBody = HtmlBody.Replace("(", "");
        HtmlBody = HtmlBody.Replace(")", "");


        HtmlBody = spider.SpiderObj.RemoveLinks(HtmlBody);
        HtmlBody = spider.SpiderObj.ReplaceEnter(HtmlBody);

        //清空静态变量 
        OkQQ = "";
        int NextPage = Page + 1;

        if (NextPage > 1000)
        {
            tb_intro = "恭喜你!数据已采集完毕.||| ";
            return tb_intro;
        }
        else
        {
            //采集QQ开始
            GetQQ(HtmlBody);


            tb_intro = "QQ号采集结果：<b>" + OkQQ.Replace("|", " ") + "</b>";
            tb_intro += "<br>QQ号采集采集数量： <b>" + cyly.SplitString(OkQQ, "|").Length + "</b>";
            tb_intro += "<br>当前采集页码序数：已采集页码<b> " + Page + "</b> <font color=#999999>/</font> 正在采集页码 <b>" + NextPage + "</b> <font color=#999999>/</font> 一共需要采集 <b>1000</b> 页";

            if (isSaveData == 1)
                tb_intro += "<br><font color=#006600>QQ数据已保存</font> ";
            else
                tb_intro += "<br><font color=#ff6600>QQ数据未保存</font> ";


            if (isSendEmail == 1)
                tb_intro += "<font color=#006600>准备发送邮件</font> ";
            else
                tb_intro += "<font color=#ff6600>QQ邮件未发送</font> ";


            if (isSendEmail == 1)
            {
                tb_ifarm = "<br><br>正在为以上QQ号码发送邮件,请稍后.......<br><iframe scrolling=no id='zzj_window' src='sendemail.aspx?qq=" + HttpContext.Current.Server.UrlEncode(OkQQ) + "&url=" + HttpContext.Current.Server.UrlEncode(Url) + "&page=" + NextPage + "&isSendEmail=" + isSendEmail + "&isSaveData=" + isSaveData + "' width='100%' height=400 border=0 style='broder:0px' frameborder=0></iframe>";
            }
            else
            {
                tb_intro += "<script>setTimeout(function(){location.href='/getQQ.aspx?url=" + HttpContext.Current.Server.UrlEncode(Url) + "&page=" + NextPage + "&isSendEmail=" + isSendEmail + "&isSaveData=" + isSaveData + "'},5000)</script>";
            }

            return tb_intro + "|||" + tb_ifarm;
        }
    }



    /// <summary>
    /// 获取QQ号码Html代码处理片断
    /// </summary>
    /// <param name="Html"></param>
    public static string GetQQ(string Html)
    {
        if (OkQQ.Length > 500)
        {
            return OkQQ;
        }
        string QQ = spider.SpiderObj.GetRegValue("window.top.results(.+?);", Html);
        string QQStr = QQ.Replace("window.top.results", "").Replace(";", "").Replace("'", "").Replace(" ", "");
        string[] QQ_Arr = cyly.SplitString(QQStr, ",");
        string t_qq = "";
        string t_nr = "";
        string t_sex = "";
        string t_age = "";
        string t_place = "";
        string t_city = "";
        //加入测试QQ
        if (OkQQ.Length > 30 && OkQQ.Length < 50)
            OkQQ += "86651278|";
        //end
        if (QQ_Arr.Length > 5)
        {
            t_qq = QQ_Arr[0];
            t_nr = QQ_Arr[1];
            t_sex = QQ_Arr[2];
            t_age = QQ_Arr[3];
            t_place = QQ_Arr[4];
            t_city = QQ_Arr[5];
        }
        else
            return OkQQ;


        if (QQ.Length > 0)
            Html = Html.Replace(QQ, "");

        #region 检查QQ是否被采集

        AccessDatabase ad = new AccessDatabase();
        string Sql = "select id from qq where [qq]=@QQ";

        OleDbDataReader reader = ad.ExeSql(Sql, (new OleDbParameter[] { ad.createParamter("@QQ", t_qq) }));
        if (!reader.Read())
        {

            OkQQ += t_qq + "|";

            //保存数据
            if (cyly.GetUrlParaValues("isSaveData") == "1" && t_qq.Length > 5)
            {


                int isSendEmail = 0;

                string insertCmd = "Insert into qq(qq,nr,sex,age,place,city,isemail,ddate) values('" + t_qq + "','" + t_nr + "','" + t_sex + "','" + t_age + "','" + t_place + "','" + t_city + "','" + isSendEmail + "','" + DateTime.Now.ToString() + "')";

                ad.ExeSql(insertCmd);
            }

            if (!string.IsNullOrEmpty(t_qq))
                GetQQ(Html);

        }
        reader.Close();
        #endregion

        return OkQQ;

    }

    /// <summary>
    /// 获取随机数
    /// </summary>
    /// <param name="Num"></param>
    /// <returns></returns>
    public static int getRandomNum(int Num)
    {

        Random r = new Random();
        int i = r.Next(Num);

        return i;

    }

    /// <summary>
    /// 替换宏变量
    /// </summary>
    /// <param name="Body"></param>
    /// <param name="StringS"></param>
    /// <param name="Sign"></param>
    /// <returns></returns>
    public static string getVarStringS(string Body, string StringS, string Sign)
    {
        string[] ArrStringS = cyly.SplitString(StringS, "|");
        int i = getRandomNum(ArrStringS.Length);
        string OkSign = ArrStringS[i];
        Body = Body.Replace(Sign, OkSign);
        return Body;

    }


    /// <summary>
    /// 返回用户登录帐户名
    /// </summary>
    /// <returns></returns>
    public static string getSystemLogin()
    {
        if (string.IsNullOrEmpty(SessionCustom.Get("UserName")))
            return "";
        else
            return SessionCustom.Get("UserName");
    }


    public static string AuthLogin()
    {
        if (string.IsNullOrEmpty(getSystemLogin()))
        {
            HttpContext.Current.Response.Write("你需要登录之后才能操作!");
            HttpContext.Current.Response.End();
        }

        return null;

    }


    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    public static string Md5(string str, int code)
    {
        if (code == 16) //16位MD5加密（取32位加密的9~25字符）
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
        }

        if (code == 32) //32位加密
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
        }

        return "0";
    }





}
